<template>
  <div class="mermaid-container" :data-diagram-type="diagramType">
    <div ref="mermaidRef" v-html="svg" v-if="svg" class="mermaid-svg-wrapper"></div>
    <pre v-else>{{ code }}</pre>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, nextTick } from 'vue';
import { useData } from 'vitepress';
import { generateMermaidConfig } from './mermaidTheme.js';

const props = defineProps({
  code: {
    type: String,
    required: true,
  },
});

const { isDark } = useData();
const mermaidRef = ref(null);
const svg = ref('');

// 识别图表类型
const diagramType = computed(() => {
  const code = props.code.toLowerCase();
  if (code.includes('statediagram-v2')) return 'state-v2';
  if (code.includes('statediagram')) return 'state';
  if (code.includes('flowchart') || code.includes('graph')) return 'flow';
  if (code.includes('sequencediagram')) return 'sequence';
  if (code.includes('gantt')) return 'gantt';
  if (code.includes('pie')) return 'pie';
  if (code.includes('erdiagram')) return 'er';
  if (code.includes('journey')) return 'journey';
  if (code.includes('classDiagram')) return 'class';
  if (code.includes('gitgraph')) return 'git';
  return 'other';
});

/**
 * 统一修复所有图表类型的标签高度问题
 * @param {SVGElement} svgElement - SVG DOM 元素
 * @param {string} type - 图表类型
 */
const fixDiagramLabels = (svgElement, type) => {
  if (!svgElement) return;

  // 定义不同图表类型的标签选择器
  const labelSelectors = {
    flow: ['.edgeLabel', '.nodeLabel', '.cluster-label'],
    er: ['.edgeLabel', '.entityLabel', '.relationshipLabel', '.attributeLabel'],
    class: ['.edgeLabel', '.nodeLabel', '.classLabel'],
    state: ['.edgeLabel', '.nodeLabel'],
    'state-v2': ['.edgeLabel', '.nodeLabel'],
    sequence: ['.messageText', '.labelText', '.loopText', '.noteText'],
    git: ['.commit-label', '.branch-label', '.tag-label'],
  };

  // 获取当前图表类型需要修复的选择器
  const selectors = labelSelectors[type] || ['.edgeLabel', '.nodeLabel'];

  // 通用的标签修复函数
  const fixLabelHeight = (label) => {
    // 查找 foreignObject 和内部内容容器
    const foreignObject = label.querySelector('foreignObject');
    if (!foreignObject) return;

    // 可能的内容容器选择器
    const contentSelectors = ['.labelBkg', '.label', 'div', 'span'];
    let labelContent = null;

    for (const selector of contentSelectors) {
      labelContent = foreignObject.querySelector(selector);
      if (labelContent) break;
    }

    if (!labelContent) return;

    // 保存原始样式
    const originalStyles = {
      display: labelContent.style.display,
      visibility: labelContent.style.visibility,
      position: labelContent.style.position,
      width: labelContent.style.width,
      height: labelContent.style.height,
      whiteSpace: labelContent.style.whiteSpace,
    };

    // 临时设置样式以获取准确尺寸
    Object.assign(labelContent.style, {
      display: 'inline-block',
      visibility: 'hidden',
      position: 'fixed',
      width: 'auto',
      height: 'auto',
      whiteSpace: 'nowrap',
      top: '0',
      left: '0',
      zIndex: '-9999',
    });

    // 强制重新计算布局
    document.body.appendChild(labelContent);

    // 获取实际尺寸
    const rect = labelContent.getBoundingClientRect();
    const textElements = labelContent.querySelectorAll('text, p, span, div');
    let maxWidth = rect.width;
    let totalHeight = rect.height;

    // 检查是否有多行文本
    textElements.forEach((el) => {
      const elRect = el.getBoundingClientRect();
      maxWidth = Math.max(maxWidth, elRect.width);
    });

    // 移回原位置并恢复样式
    foreignObject.appendChild(labelContent);
    Object.assign(labelContent.style, originalStyles);

    // 计算合适的尺寸（添加内边距）
    const padding = {
      horizontal: 12, // 左右各6px
      vertical: 8, // 上下各4px
    };

    // 特殊处理不同图表类型的内边距
    if (type === 'er') {
      padding.horizontal = 16;
      padding.vertical = 10;
    } else if (type === 'sequence') {
      padding.horizontal = 10;
      padding.vertical = 6;
    }

    const newWidth = Math.ceil(maxWidth + padding.horizontal);
    const newHeight = Math.ceil(totalHeight + padding.vertical);

    // 更新 foreignObject 的尺寸
    foreignObject.setAttribute('width', newWidth);
    foreignObject.setAttribute('height', newHeight);

    // 设置内容样式以确保正确显示
    Object.assign(labelContent.style, {
      width: `${newWidth}px`,
      height: `${newHeight}px`,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      boxSizing: 'border-box',
      padding: `${padding.vertical / 2}px ${padding.horizontal / 2}px`,
      overflow: 'visible',
      whiteSpace: 'normal',
      wordBreak: 'break-word',
      textAlign: 'center',
    });

    // 处理内部文本元素
    const innerTextElements = labelContent.querySelectorAll(
      'p, span, div.edgeLabel, div.nodeLabel'
    );
    innerTextElements.forEach((el) => {
      Object.assign(el.style, {
        margin: '0',
        padding: '0',
        lineHeight: '1.3',
        maxWidth: '100%',
      });
    });

    // ER图特殊处理：关系标签可能需要更多空间
    if (type === 'er' && label.classList.contains('relationshipLabel')) {
      const relationText = labelContent.textContent || '';
      if (relationText.length > 10) {
        foreignObject.setAttribute('width', Math.max(newWidth, 100));
        labelContent.style.width = `${Math.max(newWidth, 100)}px`;
      }
    }
  };

  // 修复所有匹配的标签
  selectors.forEach((selector) => {
    const labels = svgElement.querySelectorAll(selector);
    labels.forEach((label) => {
      // 使用 requestAnimationFrame 确保渲染完成
      requestAnimationFrame(() => {
        fixLabelHeight(label);
      });
    });
  });

  // 特殊处理：ER图的实体标签
  if (type === 'er') {
    // 修复实体框内的属性标签
    const entityGroups = svgElement.querySelectorAll('.er-entity');
    entityGroups.forEach((entity) => {
      const attributes = entity.querySelectorAll('.er-attribute');
      attributes.forEach((attr) => {
        const text = attr.querySelector('text');
        if (text) {
          text.style.fontSize = '12px';
          text.style.fontWeight = '400';
        }
      });
    });

    // 修复关系线上的标签位置
    const relationships = svgElement.querySelectorAll('.er-relationship');
    relationships.forEach((rel) => {
      const label = rel.querySelector('.relationshipLabel');
      if (label) {
        // 确保关系标签不被遮挡
        label.style.zIndex = '10';
      }
    });
  }

  // 特殊处理：序列图的消息标签
  if (type === 'sequence') {
    const messages = svgElement.querySelectorAll('.messageText');
    messages.forEach((msg) => {
      const rect = msg.getBoundingClientRect();
      if (rect.height < 20) {
        msg.style.minHeight = '20px';
        msg.style.lineHeight = '20px';
      }
    });
  }
};

// 处理特殊图表的 SVG
const processSvg = (svgString, type) => {
  // 只对状态图进行特殊处理
  if (type === 'state-v2' || type === 'state') {
    const parser = new DOMParser();
    const doc = parser.parseFromString(svgString, 'image/svg+xml');
    const svgElement = doc.querySelector('svg');

    if (svgElement) {
      const viewBox = svgElement.getAttribute('viewBox');
      if (viewBox) {
        const [x, y, width, height] = viewBox.split(' ').map(Number);
        const aspectRatio = width / height;

        const targetHeight = 400;
        const targetWidth = targetHeight * aspectRatio;

        const maxWidth = 800;
        const finalWidth = Math.min(targetWidth, maxWidth);
        const finalHeight = finalWidth / aspectRatio;

        svgElement.setAttribute('width', `${finalWidth}`);
        svgElement.setAttribute('height', `${finalHeight}`);
        svgElement.style.width = `${finalWidth}px`;
        svgElement.style.height = `${finalHeight}px`;
        svgElement.style.maxWidth = '100%';
        svgElement.style.height = 'auto';
      }

      let processedSvg = new XMLSerializer().serializeToString(doc);
      processedSvg = processedSvg
        .replace(/font-size="[\d.]+"/g, 'font-size="11"')
        .replace(/stroke-width="[\d.]+"/g, 'stroke-width="1"');

      return processedSvg;
    }
  }

  // 流程图、ER图和其他图表：只做基本处理
  if (type === 'flow' || type === 'sequence' || type === 'er' || type === 'class') {
    return svgString
      .replace(/height="[\d.]+px?"/, '')
      .replace(/width="[\d.]+px?"/, 'width="100%"')
      .replace(/style="max-width:[\d.]+px;?"/, '');
  }

  return svgString;
};

// 渲染 Mermaid 图表
const renderMermaid = async () => {
  try {
    const mermaid = await import('mermaid');
    const type = diagramType.value;

    mermaid.default.initialize(generateMermaidConfig(isDark.value, type));

    const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`;
    svg.value = '';

    const { svg: renderedSvg } = await mermaid.default.render(id, props.code);
    svg.value = processSvg(renderedSvg, type);

    // 等待 DOM 更新
    await nextTick();

    // 获取渲染后的 SVG 元素
    const svgElement = mermaidRef.value?.querySelector('svg');
    if (!svgElement) return;

    // 应用标签修复（支持多种图表类型）
    const needsLabelFix = ['flow', 'er', 'class', 'sequence', 'state', 'state-v2', 'git'];
    if (needsLabelFix.includes(type)) {
      // 延迟执行以确保 SVG 完全渲染
      setTimeout(() => {
        fixDiagramLabels(svgElement, type);
      }, 10);
    }

    // 状态图的特殊处理
    if (type === 'state-v2' || type === 'state') {
      const bbox = svgElement.getBBox();
      const aspectRatio = bbox.width / bbox.height;

      const containerWidth = mermaidRef.value.offsetWidth;
      const targetHeight = 400;
      let calculatedWidth = targetHeight * aspectRatio;

      if (calculatedWidth > containerWidth) {
        calculatedWidth = containerWidth;
        const calculatedHeight = calculatedWidth / aspectRatio;
        svgElement.style.width = `${calculatedWidth}px`;
        svgElement.style.height = `${calculatedHeight}px`;
      } else {
        svgElement.style.width = `${calculatedWidth}px`;
        svgElement.style.height = `${targetHeight}px`;
      }

      svgElement.style.maxWidth = '100%';
      svgElement.style.display = 'block';
      svgElement.style.margin = '0 auto';
    }
  } catch (error) {
    console.error('Mermaid rendering error:', error);
    console.error('Code that caused error:', props.code);
  }
};

// 组件挂载时渲染
onMounted(() => {
  renderMermaid();
});

// 监听代码变化
watch(
  () => props.code,
  () => {
    renderMermaid();
  }
);

// 监听主题变化
watch(
  () => isDark.value,
  () => {
    renderMermaid();
  }
);
</script>

<style scoped>
/* ... 保持原有的基础样式 ... */

.mermaid-container {
  margin: 2em 0;
  width: 100%;
  overflow-x: auto;
  overflow-y: visible;
}

.mermaid-svg-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  min-height: 100px;
  padding: 1em 0;
}

/* 基础 SVG 样式 */
.mermaid-container :deep(svg) {
  height: auto !important;
  font-family: 'ui-sans-serif', 'system-ui', '-apple-system', sans-serif;
}

/* ==================== 标签样式统一配置 ==================== */

/* 通用标签样式 */
.mermaid-container :deep(.edgeLabel),
.mermaid-container :deep(.nodeLabel),
.mermaid-container :deep(.relationshipLabel),
.mermaid-container :deep(.entityLabel),
.mermaid-container :deep(.attributeLabel),
.mermaid-container :deep(.classLabel) {
  font-size: 12px !important;
  font-weight: 500;
}

/* 标签容器背景 */
.mermaid-container :deep(.labelBkg),
.mermaid-container :deep(.label) {
  background-color: var(--vp-c-bg);
  border: 1px solid var(--vp-c-divider);
  border-radius: 4px;
  overflow: visible !important;
}

/* foreignObject 溢出处理 */
.mermaid-container :deep(foreignObject) {
  overflow: visible !important;
}

/* 标签内文本样式 */
.mermaid-container :deep(.edgeLabel p),
.mermaid-container :deep(.nodeLabel p),
.mermaid-container :deep(.relationshipLabel p),
.mermaid-container :deep(.entityLabel p) {
  color: var(--vp-c-text-1);
  margin: 0 !important;
  padding: 0 !important;
  line-height: 1.3 !important;
}

/* ==================== 流程图特定样式 ==================== */

.mermaid-container[data-diagram-type='flow'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='flow'] :deep(svg) {
  min-width: 400px;
  max-width: 100%;
  max-height: none !important;
  height: auto !important;
}

.mermaid-container[data-diagram-type='flow'] :deep(.edgeLabel .labelBkg) {
  background-color: var(--vp-c-bg-soft);
}

/* ==================== ER图特定样式 ==================== */

.mermaid-container[data-diagram-type='er'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='er'] :deep(svg) {
  min-width: 400px;
  max-width: 100%;
  max-height: none !important;
}

/* ER图关系标签 */
.mermaid-container[data-diagram-type='er'] :deep(.relationshipLabel) {
  z-index: 10;
  position: relative;
}

.mermaid-container[data-diagram-type='er'] :deep(.relationshipLabel .labelBkg) {
  background-color: var(--vp-c-bg);
  border: 1px solid var(--vp-c-brand);
  padding: 4px 8px !important;
}

/* ER图实体标签 */
.mermaid-container[data-diagram-type='er'] :deep(.entityLabel) {
  font-weight: 600;
  font-size: 14px !important;
}

/* ER图属性标签 */
.mermaid-container[data-diagram-type='er'] :deep(.attributeLabel) {
  font-size: 11px !important;
  font-weight: 400;
}

/* ==================== 序列图特定样式 ==================== */

.mermaid-container[data-diagram-type='sequence'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='sequence'] :deep(svg) {
  min-width: 500px;
  max-width: 100%;
  max-height: none !important;
  height: auto !important;
}

.mermaid-container[data-diagram-type='sequence'] :deep(.messageText) {
  font-size: 12px !important;
  min-height: 20px;
  line-height: 20px;
}

/* ==================== 类图特定样式 ==================== */

.mermaid-container[data-diagram-type='class'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='class'] :deep(svg) {
  min-width: 400px;
  max-width: 100%;
  max-height: none !important;
}

.mermaid-container[data-diagram-type='class'] :deep(.classLabel) {
  font-weight: 600;
  font-size: 13px !important;
}

/* ==================== 状态图特定样式 ==================== */

.mermaid-container[data-diagram-type='state-v2'],
.mermaid-container[data-diagram-type='state'] {
  display: flex;
  justify-content: center;
  align-items: center;
  max-height: 450px;
  padding: 20px 0;
  overflow-x: auto;
  overflow-y: hidden;
}

.mermaid-container[data-diagram-type='state-v2'] :deep(svg),
.mermaid-container[data-diagram-type='state'] :deep(svg) {
  max-height: 400px !important;
  width: auto !important;
  max-width: 100% !important;
  object-fit: contain;
}

/* 状态图文字颜色修复 */
.mermaid-container[data-diagram-type='state-v2'] :deep(.nodeLabel),
.mermaid-container[data-diagram-type='state'] :deep(.nodeLabel) {
  fill: var(--vp-c-text-1) !important;
  color: var(--vp-c-text-1) !important;
}

/* ==================== 深色模式特定样式 ==================== */

/* 深色模式下的标签背景 */
.dark .mermaid-container :deep(.labelBkg),
.dark .mermaid-container :deep(.label) {
  background-color: var(--vp-c-bg-soft);
  border-color: var(--vp-c-divider);
}

/* 深色模式下的文字颜色 */
.dark .mermaid-container :deep(.edgeLabel p),
.dark .mermaid-container :deep(.nodeLabel p),
.dark .mermaid-container :deep(.relationshipLabel p),
.dark .mermaid-container :deep(.entityLabel p),
.dark .mermaid-container :deep(text) {
  color: var(--vp-c-text-1);
  fill: var(--vp-c-text-1);
}

/* 深色模式下ER图关系标签 */
.dark .mermaid-container[data-diagram-type='er'] :deep(.relationshipLabel .labelBkg) {
  background-color: var(--vp-c-bg-elv);
  border-color: var(--vp-c-brand-dim);
}

/* ==================== 其他图表样式 ==================== */

/* 甘特图样式 */
.mermaid-container[data-diagram-type='gantt'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='gantt'] :deep(svg) {
  min-width: 600px;
  max-width: 100%;
  max-height: none !important;
}

/* 饼图样式 */
.mermaid-container[data-diagram-type='pie'] :deep(svg) {
  max-width: 500px;
}

/* Git图样式 */
.mermaid-container[data-diagram-type='git'] {
  max-height: none !important;
  overflow-y: visible;
}

.mermaid-container[data-diagram-type='git'] :deep(svg) {
  min-width: 500px;
  max-width: 100%;
  max-height: none !important;
}

/* ==================== 响应式和动画 ==================== */

/* 响应式设计 */
@media (max-width: 768px) {
  .mermaid-container {
    margin: 1em -1.5rem;
    padding: 0 1.5rem;
  }

  .mermaid-container[data-diagram-type='state-v2'],
  .mermaid-container[data-diagram-type='state'] {
    max-height: 400px;
  }

  .mermaid-container :deep(svg) {
    font-size: 11px !important;
  }
}

/* 滚动条样式 */
.mermaid-container::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

.mermaid-container::-webkit-scrollbar-track {
  background: var(--vp-c-bg-soft);
  border-radius: 3px;
}

.mermaid-container::-webkit-scrollbar-thumb {
  background: var(--vp-c-text-3);
  border-radius: 3px;
}

.mermaid-container::-webkit-scrollbar-thumb:hover {
  background: var(--vp-c-text-2);
}

/* 加载动画 */
.mermaid-svg-wrapper {
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 错误状态样式 */
.mermaid-container pre {
  background: var(--vp-code-block-bg);
  padding: 1em;
  border-radius: 6px;
  overflow-x: auto;
  color: var(--vp-code-block-color);
  font-size: 14px;
  line-height: 1.5;
}
</style>
